<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.subDefectCode" clearable :placeholder="$t('rework.subDefectCode')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.subDefectName" clearable :placeholder="$t('rework.subDefectName')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.defectCode" :placeholder="$t('rework.defectCode')" class="filter-item" clearable style="width: auto" @change="handleFilter">
        <el-option v-for="(item, index) in failListOptions" :key="index" :label="item" :value="item" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      :row-style="{height:'20px'}"
      :cell-style="{padding:'2px'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="$t('rework.subDefectCode')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.subDefectCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.subDefectName')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.subDefectName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.defectCode')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.defectCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.rank')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.rank }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('rework.subDefectCode')">
          <el-input v-model="temp.subDefectCode" clearable :placeholder="$t('rework.subDefectCode')" />
        </el-form-item>
        <el-form-item :label="$t('rework.subDefectName')">
          <el-input v-model="temp.subDefectName" clearable :placeholder="$t('rework.subDefectName')" />
        </el-form-item>
        <el-form-item :label="$t('rework.defectCode')" required prop="defectCode">
          <el-select v-model="temp.defectCode" :placeholder="$t('rework.defectCode')" class="filter-item" clearable="" style="width: 450px">
            <el-option v-for="(item, index) in failListOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('rework.rank')">
          <el-input v-model="temp.rank" clearable :placeholder="$t('rework.rank')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getPendingOrderList, creatPendingOrderList, updatePendingOrderList, deletePendingOrderList } from '@/api/order'
import { getSubFailList, creatSubFailList, updateSubFailList, deleteSubFailList, getFailList } from '@/api/rework'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'FailDetail',
  components: {
    Pagination
  },
  directives: { waves },
  // filters: {
  //   statusFilter(status) {
  //     const statusMap = {
  //       published: 'success',
  //       draft: 'info',
  //       deleted: 'danger'
  //     }
  //     return statusMap[status]
  //   }
  // },
  data() {
    return {
      list: [],
      // date: '',
      // time: '',
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        defectCode: '',
        subDefectCode: '',
        subDefectName: '',
        lineNumber: ''
      },
      temp: {
        defectCode: '',
        subDefectCode: '',
        subDefectName: '',
        rank: 0,
        lineNumber: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      failListOptions: [],
      rules: {
        defectCode: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      }
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.params.defectCode !== undefined) {
          console.log(this.$route.params.defectCode)
          this.listQuery.defectCode = this.$route.params.defectCode
          this.getList()
        }
      }
    }
  },
  created() {
    // 获取线号
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.temp.lineNumber = this.$store.getters.lineNumber
    // this.listQuery.orderCode = this.$route.params.orderCode
    this.getList()
    getFailList(this.listQuery).then(response => {
      const arr = response.data.fails
      arr.forEach(e => {
        if (this.failListOptions.indexOf(e.defectCode) === -1) this.failListOptions.push(e.defectCode)
      })
    })
  },
  methods: {
    // 获取子不合格定义
    getList() {
      this.listLoading = true
      getSubFailList(this.listQuery).then(res => {
        this.list = res.data.subdef
        this.total = res.data.subdef.length
        this.listLoading = false
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        defectCode: '',
        subDefectCode: '',
        subDefectName: '',
        rank: 0,
        lineNumber: this.$store.getters.lineNumber
      }
    },
    // 新建一条线体
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      //   this.temp.manager = this.$store.getters.name
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatSubFailList(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.date = this.temp.customerSnCreateTime.substring(0, 10)
      this.time = this.temp.customerSnCreateTime.substring(this.temp.customerSnCreateTime.length - 8, this.temp.customerSnCreateTime.length)
      console.log(this.time)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lineNumber = this.$store.getters.lineNumber
          updateSubFailList(this.temp).then(response => {
            const index = this.list.findIndex(v => v.subDefectCode === this.temp.subDefectCode)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            console.log(this.list)
            this.getList()
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          this.temp.lineNumber = this.$store.getters.lineNumber
          deleteSubFailList(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    }
  }
}
</script>

<style lang="scss" scoped>
.icon-star {
  margin-right: 2px;
}
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d {
  margin-top: 15px;
}

.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
